//
//  AppIntent.swift
//  UsWidget
//
//  Created by karry on 2025/6/13.
//

import WidgetKit
import AppIntents
import Foundation


struct USMemorialDayModel: AppEntity, Identifiable {
    
    var id: String
    var name: String
    var color: String
    var repeatYearly:Bool
    var dateStr:String

    static var typeDisplayRepresentation: TypeDisplayRepresentation {
        "纪念日"
    }

    var displayRepresentation: DisplayRepresentation {
        DisplayRepresentation(title: LocalizedStringResource(stringLiteral: name))
    }

    static var defaultValue: USMemorialDayModel {
        USMemorialDayModel(id: "default", name: "纪念日",color:"D55757",repeatYearly:true,dateStr:"")
    }
    
    typealias DefaultQuery = MemorialDayQuery
    
    static var defaultQuery: DefaultQuery = MemorialDayQuery()

    struct MemorialDayQuery: EntityQuery {
        func entities(for identifiers: [USMemorialDayModel.ID]) async throws -> [USMemorialDayModel] {
            return USMemorialDayModel.getStoredModels().filter { identifiers.contains($0.id) }
        }

        func suggestedEntities() async throws -> [USMemorialDayModel] {
            return USMemorialDayModel.getStoredModels()
        }
    }

    static func getStoredModels() -> [USMemorialDayModel] {
        guard let defaults = UserDefaults(suiteName: "group.emmo.us"),
              let data = defaults.data(forKey: "memorialDayList") else {
            print("❌ 未找到 UserDefaults 中的 memorialDayList 数据")
            return []
        }

        guard let jsonArray = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else {
            print("❌ JSON 解析失败")
            return []
        }

        print("✅ 读取到纪念日 JSON 数组: \(jsonArray)")

        let models = jsonArray.compactMap { dict -> USMemorialDayModel? in
            guard let id = dict["anniversaryId"] as? String,
                  let name = dict["anniversaryName"] as? String,
                  let color = dict["color"] as?String,
                  let dateStr = dict["anniversaryDate"] as?String
            
            else {
                print("⚠️ 无效数据: \(dict)")
                return nil
            }
            let repeatYearly = (dict["repeatYearly"] as? Int) == 1
            return USMemorialDayModel(id: id, name: name,color:color,repeatYearly:repeatYearly,dateStr:dateStr)
        }
        print("✅ 成功解析 \(models.count) 条纪念日数据")
        return models
    }
    
    func dayDescription() -> String {
        guard let timestamp = TimeInterval(dateStr), timestamp > 0 else { return "" }
        let date = Date(timeIntervalSince1970: timestamp)
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "zh_CN")

        if repeatYearly {
            formatter.dateFormat = "M月d日"
            return "每年" + formatter.string(from: date)
        } else {
            formatter.dateStyle = .medium
            formatter.timeStyle = .none
            return formatter.string(from: date)
        }
    }

    func dayCount(includeStart: Bool = true) -> Int {
        guard let timestamp = TimeInterval(dateStr), timestamp > 0 else { return 1 }
        
        let calendar = Calendar.current
        let today = calendar.startOfDay(for: Date())
        let anniversary = calendar.startOfDay(for: Date(timeIntervalSince1970: timestamp))
        
        if repeatYearly {
            // 取出今年的周年日
            var todayComponents = calendar.dateComponents([.year, .month, .day], from: today)
            let annivComponents = calendar.dateComponents([.month, .day], from: anniversary)
            todayComponents.month = annivComponents.month
            todayComponents.day = annivComponents.day
            
            let thisYearAnniv = calendar.date(from: todayComponents) ?? anniversary
            
            // 若已过去，则对比明年的
            let targetDate = today <= thisYearAnniv ? thisYearAnniv : calendar.date(byAdding: .year, value: 1, to: thisYearAnniv)!
            let diff = calendar.dateComponents([.day], from: today, to: targetDate).day ?? 0
            return includeStart ? diff + 1 : diff
        } else {
            var diff = calendar.dateComponents([.day], from: anniversary, to: today).day ?? 0
            diff = abs(diff)
            return includeStart ? diff + 1 : diff
        }
    }
    
}

struct USMemorialDaySelectionIntent: WidgetConfigurationIntent {
    static var title: LocalizedStringResource { "选择纪念日" }

    static var description: IntentDescription {
        IntentDescription("你可以从多个纪念日中选择一个显示在桌面小组件上")
    }

    @Parameter(title: "纪念日")
    var anniversary: USMemorialDayModel?
}
